/*
 * Copyright 2004-2005 asoft
 * 本软件及其所有拷贝的名称，与光盘上或本软件中注明的公司同在。
 * 本软件及文档享有版权，并受国家版权法及国际协约条款的保护。
 * 您不可以从本软件中去掉其版权声明；并保证为本软件的拷贝（本部或部分）* 复制版权声明。
 * 您同意制止以任何形式非法拷贝本软件及文档。
 * 版权信息参见：
 *      http://www.asoft.cn/licenses
 */

package com.asoft.common.templet;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.testng.Assert;

import com.asoft.common.base.dao.DAO;
import com.asoft.common.base.model.BaseObject;
import com.asoft.common.sysframe.manager.OrgManager;
import com.asoft.common.sysframe.manager.PostManager;
import com.asoft.common.sysframe.manager.RoleManager;
import com.asoft.common.sysframe.manager.UserManager;
import com.asoft.common.sysframe.model.User;


/**
 * dao单元测试用例模板
 *
 * @author amonlei
 *
 */

public abstract class DAOTestCaseTemplet extends AbstractTestCaseTemplet
{
        static Logger logger = Logger.getLogger(DAOTestCaseTemplet.class);
        
        protected DAO dao;
        
        // 预先写入库的model，给update,get,delete等方法使用
        protected BaseObject preSavedBaseObject;
        
        protected Session session;

        private static UserManager userManager;
        
        private static OrgManager orgManager;
        
        private static RoleManager roleManager;
        
        private static PostManager postManager;
        
        // 当前事务状态
        private TransactionStatus ts;
        
        public void setUp(String[] springxmls)
        {
                this.initSpring(springxmls);
                this.initHbSession();
                this.beginTran();// 开启事务
                this.initSysframe();
                this.commit();
                this.beginTran();
        }
        
        public void tearDown()
        {
                this.rollback();
        }
        
        public void initSpring(String[] xmls)
        {
                if(this.getApplicationContext() == null)
                {
                        this.setApplicationContext(this.getApplicationContextFromIocXmls(xmls));
                        orgManager = (OrgManager)this.getBeanFromSpring("orgManager");
                        roleManager = (RoleManager)this.getBeanFromSpring("roleManager");
                        postManager = (PostManager)this.getBeanFromSpring("postManager");
                        userManager = (UserManager)this.getBeanFromSpring("userManager");
                }
        }       
        
        public void initHbSession()
        {
                // open session in view 
                SessionFactory sessionFactory = (SessionFactory)this.getBeanFromSpring("sessionFactory");
                session = sessionFactory.openSession();
//                TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
        }
        
        // 初始化系统数据
        public abstract void initSysframe();
        
        // 事务用
        private TransactionDefinition getDefinition(int isolationLevel)
        {
                DefaultTransactionDefinition def = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
                return def;
        }
        
        public void beginTran()
        {
                PlatformTransactionManager trm = (HibernateTransactionManager)this.getBeanFromSpring("transactionManager");
                this.ts = trm.getTransaction(getDefinition(TransactionDefinition.ISOLATION_DEFAULT));
        }
        
        public void rollback()
        {
                logger.debug("回滚还原数据库");
                PlatformTransactionManager trm = (HibernateTransactionManager)this.getBeanFromSpring("transactionManager");
                trm.rollback(ts);
        }
        
        public void commit()
        {
                PlatformTransactionManager trm = (HibernateTransactionManager)this.getBeanFromSpring("transactionManager");
                trm.commit(ts);
        }
        
        public void addPreBo()
        {
                logger.debug("initBeforeMethod()");
                Assert.assertNotNull(this.dao);
                Assert.assertNotNull(this.preSavedBaseObject);
                this.initBaseObjectWithSysInfo(this.preSavedBaseObject);
                this.dao.save(this.preSavedBaseObject);
        }

        public void delPreBo()
        {
                logger.debug("initAfterMethod()");
                Assert.assertNotNull(this.dao);
                Assert.assertNotNull(this.preSavedBaseObject);
                this.dao.remove(this.preSavedBaseObject);
        }
        
        public User getAdmin()
        {
                return userManager.getByAccount("admin");
        }

        // 初始化bo(创建人，创建时间，最后创建人，最后创建时间，优先级)
        public void initBaseObjectWithSysInfo(BaseObject bo)
        {
                logger.debug("初始化bo SysInfo");
                User admin = this.getAdmin();
                if(admin == null)
                        Assert.fail("尚未初始化系统数据");
                bo.setCreateOrg(admin.getFirstOrg());
                bo.setCreator(admin);
                bo.setCreateTime(this.now());
                
                bo.setLastUpdateOrg(admin.getFirstOrg());
                bo.setLastUpdator(admin);
                bo.setLastUpdateTime(this.now());
                
                bo.setPri(Long.toString(System.currentTimeMillis()));
        }
        
        // 删除byCode
        public void removeByCode(DAO dao,String code)
        {
                dao.remove(dao.getByCode(code));
        }
}
